package com.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

/**
 * @author liangzj
 * @date 2021/3/28 16:22
 */
public class StaticResourceUtil {

    /**
     * 获取静态资源绝对路径
     *
     * @param path
     * @return
     */
    public static String getAbsolutePath(String path) {
        String absolutePath = StaticResourceUtil.class.getResource("/").getPath();
        return absolutePath.replaceAll("\\\\", "/") + path;
    }

    /**
     * 输出指定文件
     *
     * @param sourceFileStream   输出源文件
     * @param targetOutputStream 输出目标
     * @throws IOException
     */
    public static void outputStaticResource(InputStream sourceFileStream, OutputStream targetOutputStream)
            throws IOException {
        int count = 0;
        while (count == 0) {
            count = sourceFileStream.available();
        }

        int resourceSize = count;
        // 输出请求头
        targetOutputStream.write(HttpProtocolMocker.mockHttpHeader200(resourceSize).getBytes(StandardCharsets.UTF_8));

        writeSourceFile(sourceFileStream, targetOutputStream, resourceSize);
    }

    /**
     * 将源文件通过输出流输出
     *
     * @param sourceFileStream
     * @param targetOutputStream
     * @param resourceSize       源文件字节数
     * @throws IOException
     */
    private static void writeSourceFile(InputStream sourceFileStream, OutputStream targetOutputStream, int resourceSize)
            throws IOException {
        // 读取输出内容
        long written = 0; // 已读取内容长度
        int buffSize = 1024; // 每次缓冲长度
        byte[] buffBytes = new byte[buffSize];

        while (written < resourceSize) {
            // 说明剩余未读取大小不足1024个字节，那么就按照真是长度
            if (written + buffSize > resourceSize) {
                buffBytes = new byte[(int) (resourceSize - written)];
            }

            // 读取指定字节数据并输出
            sourceFileStream.read(buffBytes);
            targetOutputStream.write(buffBytes);
            targetOutputStream.flush();

            // 更新已读取内容长度
            written += buffSize;
        }
    }

}
